/**
 * Copyright (C) 2007 geolabs
 *
 * Textarea static class
 *
 */

Textarea=Class.create({
  getSelectionStart: function(){
      var element=System.document.getElementById(arguments[0]);
      if ( typeof element.selectionStart != 'undefined' )
	return element.selectionStart;
      else{
	element.focus();
	var range = element.createTextRange();
	range.moveToBookmark(document.selection.createRange().getBookmark());
	range.moveEnd('character', element.value.length);
	return element.value.length - range.text.length;
      }
    },
  getSelectionEnd: function(){
      var element=System.document.getElementById(arguments[0]);
      if ( typeof element.selectionStart != 'undefined' )
	return element.selectionEnd;
      else{
	element.focus();
	var range = element.createTextRange();
	range.moveToBookmark(document.selection.createRange().getBookmark());
	range.moveStart('character', - element.value.length);
	return range.text.length;
      }
    },
  getSelection: function (){
      var element=System.document.getElementById(arguments[0]);
      if (element.setSelectionRange)
	return element.value.substring(element.selectionStart, element.selectionEnd);
      else if (System.document.selection) {
	element.focus();
	return System.document.selection.createRange().text;
      }
    },
  setCaretPos: function(){
      var element=System.document.getElementById(arguments[0]);
      var start=arguments[1];
      var end=null;
      if(arguments.length>2)
	end=arguments[2];
      end = end || start;
      element.focus();
      if (element.setSelectionRange)
	element.setSelectionRange(start, end);
      else if (document.selection) {
	var range = element.createTextRange();
	range.moveStart('character', start);
	range.moveEnd('character', - element.value.length + end);
	range.select();
      }
    },
  replaceSelection: function (){
      var element=System.document.getElementById(arguments[0]);
      var substitute=arguments[1];
      
      element.focus();

      if ( typeof element.selectionStart != 'undefined' ){
	var sstart = this.getSelectionStart(arguments[0]);
	var send = this.getSelectionEnd(arguments[0]);
	//alert('['+sstart+','+send+']');
	var end = sstart + substitute.length;
	var scrollPos = element.scrollTop;
	
	//alert(lastIndexOf('(',substitute));
	//if(lastIndexOf('(',substitute)===false)
	element.value = element.value.substring(0,sstart) + substitute + element.value.substring(send);
	//alert("element.value.substring(send)=>"+element.value.substring(send));
	this.setCaretPos(arguments[0],end);
	element.scrollTop = scrollPos;
      }
      else{
	range = System.document.selection.createRange();
	range.text = substitute;
	element.focus();
      }
    }
  });
